#include <stdio.h>
#include <circapi.h>
#define eprintf printf

int dispatch (int s, const char *line) {
	char *nick1;
	char *nick2;
	char buf[1024];
	char channel[1024];
	char nick[1024];
	int ret;

	switch (irc_translate (line)) {
	case PING_MSG:
		buf[0] = 0;
		irc_ping_responce (line, buf);
		ret = irc_send_server_text (s, buf);
		if (ret<1)
			eprintf ("Unable to reply ping\n");
		eprintf ("==> PINGPONG\n");
		return 1;
	case USER_PRIVMSG_MSG:
		irc_sender_message (line, buf);
		irc_sender_nick (line, nick);
		//irc_sender_ip (line, ip);
		irc_sender_channel (line, channel);
		printf ("<%s> %s\n", channel, nick, buf);
		break;
	case CHANNEL_PRIVMSG_MSG:
		irc_sender_message (line, buf);
		irc_sender_nick (line, nick);
		//irc_sender_ip (line, ip);
		irc_sender_channel (line, channel);
		printf ("%s:<%s> (%s)\n", channel, nick, buf);
		break;
	case USER_JOIN_MSG:
		printf ("[>>] %s\n",
			join_message_index_nick (line));
		break;
	case USER_PART_MSG:
		printf ("[<<] %s\n",
			join_message_index_nick (line));
		break;
	case USER_QUIT_MSG:
		printf ("[QUIT] %s\n",
			join_message_index_nick (line));
		break;
	case USER_NICK_CHANGE_MSG:
index2string (nick2, nick_change_index_oldnick (line));
index2string (nick1, nick_change_index_newnick (line));
		printf ("mv %s %s\n", nick2, nick1);
		break;
default:
printf ("-- %s\n", line);
	}
}
int main() {
	char buf[4096];
	int i, ret, s;
	struct ircofs ofs;
	const char *host = "irc.freenode.net";
	const char *port = "6667";
	const char *nick = "cpancake";
	const char *name = "nopcode";
	ret = irc_connect (&s, host, port, nick, name, 0, NULL, 0);
	if (ret<1) {
		eprintf ("unable to connect\n");
		return 1;
	}
irc_join_channel (&s, "#radare");
	while (1) {
		ret = irc_get_server_text (&s, buf, sizeof (buf));
		irc_ircofs_init (&ofs);
		irc_buff2ircofs (&ofs, buf); // parse text
		for (i=0; i<ofs.line_ct; i++) {
			ret = dispatch (s, ofs.ln[i]);
			switch (ret) {
			case -1:
				eprintf ("Disconnected\n");
				return 1;
			case 0:
				eprintf ("Client error: %s\n", ofs.ln[i]);
				break;
			}
		}
	}
	return 0;
}
